<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Admin\Metrics\Examples;

use App\Models\MemberTopupOrder;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Metrics\Bar;
use Illuminate\Http\Request;

class Sessions extends Bar
{
    /**
     * 处理请求
     *
     * @return mixed|void
     */
    public function handle(Request $request)
    {
        switch ($request->get('option')) {
            case '7':
                $res = $this->calculation(now()->startOfWeek(), now()->endOfDay());
                break;
            case '30':
                //月
                $res = $this->calculation(now()->startOfMonth(), now()->endOfDay());
                break;
            case '90':
                $res = $this->calculation(now()->startOfQuarter(), now()->endOfDay());
                break;
            case '365':
                $res = $this->calculation(now()->startOfYear(), now()->endOfDay());
                break;
            case '0':
                $res = $this->calculation(now()->startOfDay(), now()->endOfDay());
                break;
            case '999':
                $res = $this->calculation(now()->startOfDecade(), now()->endOfDay());
                break;
            default:
                $res = $this->calculation(now()->startOfDay(), now()->endOfDay());
                break;
        }
        // 卡片内容
        $this->withContent(...$res['content']);

        // 图表数据
        $this->withChart([
            [
                'name' => '充值订单',
                'data' => $res['data'],
            ],
        ]);
    }

    /**
     * 设置图表数据.
     *
     * @return $this
     */
    public function withChart(array $data)
    {
        return $this->chart([
            'series' => $data,
        ]);
    }

    /**
     * 设置卡片内容.
     *
     * @param string $title
     * @param string $value
     * @param string $style
     *
     * @return $this
     */
    public function withContent($title, $value, $style = 'success')
    {
        // 根据选项显示
        $label = '对比昨日';
        if (request()->option != 0) {
            $label = '';
            $value = '';
        }
        $url = admin_url('member_topup_orders');
        $minHeight = '183px';
        return $this->content(
            <<<HTML
<div class="d-flex p-1 flex-column justify-content-between" style="padding-top: 0;width: 100%;height: 100%;min-height: {$minHeight}">
    <div class="text-left">
        <h1 class="font-lg-2 mt-2 mb-0">{$title}</h1>
        <h5 class="font-medium-2" style="margin-top: 10px;">
            <span class="text-{$style}">{$value} </span>
            <span>{$label}</span>
        </h5>
    </div>

    <a href="{$url}" class="btn btn-primary shadow waves-effect waves-light">去查看<i class="feather icon-chevrons-right"></i></a>
</div>
HTML
        );
    }

    /**
     * 初始化卡片内容.
     */
    protected function init()
    {
        parent::init();

        $color = Admin::color();

        $dark35 = $color->dark35();

        // 卡片内容宽度
        $this->contentWidth(5, 7);
        // 标题
        $this->title('充值订单');
        // 设置下拉选项
        $this->dropdown([
            '0' => '今日',
            '7' => '周',
            '30' => '月',
            '90' => '季度',
            '365' => '年',
            '999' => '全部',
        ]);
        // 设置图表颜色
        $this->chartColors([
            $dark35,
            $dark35,
            $color->primary(),
            $dark35,
            $dark35,
            $dark35,
        ]);
    }

    private function calculation(\Illuminate\Support\Carbon $startOfDecade, \Illuminate\Support\Carbon $endOfDay)
    {
        $model = MemberTopupOrder::query()->where('review', 1)->get();
        $content = $model->whereBetween('created_at', [$startOfDecade, $endOfDay])->sum('amount');
        $lastContent = $model->whereBetween('created_at', [$startOfDecade->subDay()->startOfDay(), $endOfDay->subDays()->endOfDay()])->sum('amount');
        if ($lastContent == 0) {
            $lastContent = 1;
        }
        $rate = bcdiv($content, $lastContent, 2);
        $data = $model
            ->whereBetween('created_at', [$startOfDecade, $endOfDay])
            ->map(function ($item) {
                $item['date'] = now()->setDateFrom($item->created_at)->format('Y-m-d');
                return $item;
            })->groupBy('date')->map(function ($item) {
                return $item->sum('amount');
            });
        if ($rate >= 1) {
            $r = "+{$rate}";
            $style = 'success';
        } else {
            $r = "-{$rate}";
            $style = 'danger';
        }
        return [
            'content' => [
                $content,
                $r,
                $style,
            ],
            'data' => $data,
        ];
    }
}
